<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\DrainageLink\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkRoom\Event\CreateRoomMemberEvent;
use MoChat\Plugin\AutoTag\Action\Dashboard\Traits\AutoContactTag;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContactContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContract;
use MoChat\Plugin\RoomAutoPull\Contract\WorkRoomAutoPullContract;
use Psr\Container\ContainerInterface;

/**
 * 客户群创建事件
 * 有新增客户群时，回调该事件。收到该事件后，企业可以调用获取客户群详情接口获取客户群详情。
 * @Listener
 */
class CreateRoomMemberListener implements ListenerInterface
{
    use AutoContactTag;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @var DrainageLinkContactContract
     */
    protected $drainageLinkContactService;

    /**
     * @var WorkRoomAutoPullContract
     */
    protected $workRoomAutoPullService;

    /**
     * @var DrainageLinkContract
     */
    protected $drainageLinkService;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    public function listen(): array
    {
        return [
            CreateRoomMemberEvent::class,
        ];
    }

    /**
     * @param CreateRoomMemberEvent $event
     */
    public function process(object $event)
    {
        try {
            $message = $event->message;
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->workEmployeeService = $this->container->get(WorkEmployeeContract::class);
            $this->workContactService = $this->container->get(WorkContactContract::class);
            $this->workContactEmployeeService = $this->container->get(WorkContactEmployeeContract::class);
            $this->drainageLinkService = $this->container->get(DrainageLinkContract::class);
            $this->drainageLinkContactService = $this->container->get(DrainageLinkContactContract::class);
            $this->workRoomAutoPullService = $this->container->get(WorkRoomAutoPullContract::class);

            $corpId = $message['corpId'];
            $rooms = $message['rooms'];

            if (empty($rooms)) {
                return [];
            }

            $drainageLink = $this->drainageLinkService->getDrainageLinkByTypeQrcodeType(2, 2, ['id', 'qrcode_id']);
            foreach ($drainageLink as $k => $v) {
                $workRooms = $this->workRoomAutoPullService->getWorkRoomAutoPullById($v['qrcodeId'], ['rooms']);
                $drainageLink[$k]['roomId'] = array_column(Json::decode($workRooms['rooms']), 'roomId');
            }

            // 开启事物
            Db::beginTransaction();
            foreach ($rooms as $item) {
                if ($item['contact_id'] === 0) {
                    continue;
                }
                foreach ($drainageLink as $link) {
                    if (in_array($item['room_id'], $link['roomId'], true)) {
                        $data = [
                            'link_id' => $link['id'],
                            'contact_id' => $item['contact_id'],
                            'room_id' => $item['room_id'],
                            'created_at' => date('Y-m-d H:i:s'),
                        ];
                        $this->drainageLinkContactService->createDrainageLinkContact($data);
                    }
                }
            }

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('[引流链接]统计引流入群失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
